import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { baseURL } from '@/utils/request';
import { getTokenInfo } from '@/utils/storage';
import { Toast } from 'antd-mobile';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import { io, Socket } from 'socket.io-client';
import styles from './index.module.scss';

export default function Chat() {
  type msgList = {
    msg: string;
    type: string;
    timestamp: number;
  };
  //创建ref  Socket是只读类型,null告诉ts我是告诉给null 分配socket
  const sockRef = useRef<Socket | null>(null);
  useEffect(() => {
    sockRef.current = io(baseURL, {
      query: {
        token: getTokenInfo(),
      },
      transports: ['websocket'],
    });
    sockRef.current.on('connect', () => {
      // 第一次连接成功后的回调
      setMagList([
        { msg: '欢迎来到小智的聊天室', type: 'robot', timestamp: Date.now() },
      ]);
    });
    // 监听服务器发送的消息,显示在界面上
    sockRef.current.on('message', (data) => {
      setMagList((preMsgList) => {
        //🔔 异步行为，会覆盖掉旧的数据，使用函数的写法更新
        return [...preMsgList, { ...data, type: 'robot' }];
      });
    });
    return () => {
      sockRef.current?.close();
    };
  }, []);

  const [magList, setMagList] = useState<msgList[]>([]);
  const [mag, setMag] = useState('');
  //监听数据变化时
  useEffect(() => {
    console.log('1  ----->  ', 1);
    window.scroll({
      // scrollHeight表示超出视口的内容高度，可以理解为，能滚动多少就滚动多少
      top: document.body.scrollHeight,
      // 变化 平滑的
      behavior: 'smooth',
    });
  }, [magList]);

  const handleSubmit = () => {
    // 非空判断
    if (!mag.trim()) {
      Toast.show({ content: '消息不能为空' });
      return;
    }
    setMagList([...magList, { msg: mag, type: 'user', timestamp: Date.now() }]);
    // 3发送内容
    sockRef.current?.emit('message', {
      msg: mag,
      timestamp: Date.now(),
    });
    setMag('');
  };
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSubmit();
    }
  };
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list">
        {/* 机器人的消息 */}
        {magList.map((item) => {
          return (
            <div
              className={classNames('chat-item', {
                user: item.type === 'user',
              })}
              key={item.timestamp}
            >
              {item.type === 'user' ? (
                <Icon type="iconbtn_xiaozhitongxue" />
              ) : (
                <img
                  src={'http://toutiao.itheima.net/images/user_head.jpg'}
                  alt=""
                />
              )}
              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        {/* 底部消息输入框 */}
        <div className="input-footer">
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={mag}
            onChange={(e) => setMag(e.target.value)}
            onKeyDown={(e) => handleKeyDown(e)}
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={handleSubmit}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
